<template>
  <view class="container">
    <view v-if="error != ''" style="position: absolute;top: 0;left: 0;">
      {{error == ''? '': errorProgress + error}}
    </view>

    <!-- <image src="../../static/icon/login.png" mode="scaleToFill" class="icon"></image> -->
    <view class="content">
      <!--  #ifdef  MP-WEIXIN -->
      <button open-type='getPhoneNumber' @getphonenumber="getPhoneNumber" :loading="getPhoneNumberLoading"
        :disabled="getPhoneNumberLoading">
        授权登录
      </button>
      <!--  #endif -->

      <!--  #ifdef  MP-ALIPAY -->
      <button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
        授权登录
      </button>
      <!--  #endif -->
      <button type="default">手机登录</button>
      <text>登录即代表同意《隐私政策》和《用户服务协议》</text>
    </view>
  </view>
</template>
<script>
  import {
    mapState,
    mapMutations
  } from "vuex";
  import WXBizDataCrypt from "./WXBizDataCrypt.js"

  export default {
    data() {
      return {
        code: '',
        getPhoneNumberLoading: false,
        error: '',
        errorProgress: 0
      }
    },
    async onShow() {
      // 获得code有效码
      // let [err, loginData] = await uni.login();
      // this.code = loginData.code;
      this.getAppid();
    },
    computed: {},
    async created() {
      // if (!!this.phoneNumber && this.phoneNumber.length === 11) {
      //   uni.redirectTo({
      //     url: "/pages/index/index"
      //   })
      //   return
      // }
      
    },
    methods: {
      ...mapMutations({
        updateOpenId: "updateOpenId",
        updateUnionId: "updateUnionId",
        updateUserInfo: "updateUserInfo",
        updatePhoneNumber: "updatePhoneNumber",
        updateCountryCode: "updateCountryCode",
        updatePurePhoneNumber: "updatePurePhoneNumber",
        resetApplet: "resetApplet",
        clearUserAuthen: "clearUserAuthen"
      }),
      async getAppid() {
        const this_ = this;
        uni.login({
          provider: 'weixin',
          success: async (res) => {
            this_.updateCountryCode(res.code);
            this_.code = res.code;
            const gzhAuthenRes = await this.$Request({
              url: "/getPaySessionKeyAndOpenID",
              method: "GET",
              data: {
                code: res.code,
              }
            });
            if (gzhAuthenRes.retCode === 0) {
              const openId = gzhAuthenRes.data.openid;
              this_.session_key=gzhAuthenRes.data.sessionKey 
              this_.updateOpenId(openId)
            }
            // this_.code = res.code;
            // uni.request({  
            //   url: 'https://api.weixin.qq.com/sns/jscode2session',  
            //   method:'GET',  
            //   data: {
            //     appid: 'wx3d56fc8b214444d2',
            //     secret: 'f822422940490b23e7d5f3f39942ad07', 
            //     js_code: res.code,
            //     grant_type: 'authorization_code',
            //   },  
            //   success: (cts) => {  
            //     // 换取成功后 暂存这些数据 留作后续操作  
            //     const openId=cts.data.openid               //openid 用户唯一标识  
            //     this_.session_key=cts.data.session_key     //session_key  会话密钥  
            //     this_.updateOpenId(openId)
            //   }  
            // });
          }
        });
        
      },
      //#ifdef MP-WEIXIN 
      //新登录接口 服务端也写好了，适当的时候启用
      async getPhoneNumber(info) {
        this.getPhoneNumberLoading = true;
        uni.showLoading({
          title: '获取中...',
          mask: true
        });
        console.log(info, '---', this);
        this.errorProgress = 1
        if (info.detail.errMsg === "getPhoneNumber:ok") {
          try {
            let pc = new WXBizDataCrypt('wx3d56fc8b214444d2',this.session_key);
            let data = pc.decryptData(info.detail.encryptedData , info.detail.iv);  
            console.log(data, 'dataaaaaa');
            const encryptedData = info.detail.encryptedData;
            const iv = info.detail.iv;
            const infoData = await this.$Request({
              url: "/loginGetPhone",
              method: "GET",
              data: {
                code: this.code,
                // stationId: this.stationId,
                stationId: 223, // 待调整
                encryptedData,
                iv,
                version: 2, 
                "blogNickName": this.userInfo.nickName,
                "sexFlag": this.userInfo.gender,
                "blogProfilePhoto": this.userInfo.avatarUrl,
              }
            })
            const phone = data.phoneNumber;
            this.updatePhoneNumber(phone)
              
            this.getPhoneNumberLoading = false
            this.errorProgress = 4
            uni.hideLoading();
            this.errorProgress = 5
            uni.redirectTo({
              url: "/subPack/my/my"
            })
          } catch (e) {
            this.errorProgress += ("-" +
              wx.getSystemInfoSync().version + '-' // 微信版本
              +
              wx.getSystemInfoSync().model + '-' // 设备
              +
              wx.getSystemInfoSync().system + '-' // 系统
              +
              wx.getSystemInfoSync().SDKVersion + '-') // sdk
            this.getPhoneNumberLoading = false
            uni.hideLoading();
            this.error = e.message;
            uni.showToast({
              // title: '请重新授权',
              title: e.message,
              icon: "error"
            })
            let [err, loginData] = await uni.login();
            this.code = loginData.code
            this.clearUserAuthen();
          }
        } else {
          this.getPhoneNumberLoading = false
          uni.hideLoading();
          uni.showToast({
            title: '请授权登录~',
            icon: "error"
          })
        }
      },
      //#endif
    },
  }
</script>
<style lang="scss">
  page {
    width: 750rpx;
    background-color: #f0f2f5;
    min-height: 100vh;

    .container {
      text-align: center;

      .icon {
        margin-top: 414rpx;
        width: 508rpx;
        height: 388rpx;
        margin-top: 180rpx;
        display: inline-block;
      }

      .content {
        display: inline-flex;
        flex-direction: column;
        justify-content: center;
        margin-top: 210rpx;

        button:nth-child(1) {
          width: 616rpx;
          height: 76rpx;
          background: linear-gradient(123deg, #12A273 0%, #12A273 100%);
          border-radius: 38rpx;
          font-size: 32rpx;
          color: #FFFFFF;
          line-height: 76rpx;
        }

        button:nth-child(2) {
          width: 616rpx;
          height: 76rpx;
          background-color: #f0f2f5;
          border-radius: 38rpx;
          font-size: 32rpx;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.25);
          line-height: 76rpx;
        }

        text {
          margin-top: 42rpx;
          height: 36rpx;
          font-size: 26rpx;
          color: rgba(0, 0, 0, 0.5);
          line-height: 36rpx;
        }
      }
    }
  }
</style>
